package com.cicc.wm.lock.redis;

import com.cicc.wm.lock.DistributedLock;
import org.redisson.api.RLock;

import java.util.concurrent.TimeUnit;

/**
 * Redisson分布式锁适配器
 * 将Redisson的RLock适配为DistributedLock接口
 */
public class RedisDistributedLock implements DistributedLock {
    private final RLock redissonLock;

    public RedisDistributedLock(RLock redissonLock) {
        this.redissonLock = redissonLock;
    }

    @Override
    public void lock() {
        redissonLock.lock();
    }

    @Override
    public void lock(long leaseTime, TimeUnit timeUnit) {
        redissonLock.lock(leaseTime, timeUnit);
    }

    @Override
    public boolean tryLock() {
        return redissonLock.tryLock();
    }

    @Override
    public boolean tryLock(long waitTime, TimeUnit unit) throws InterruptedException {
        return redissonLock.tryLock(waitTime, unit);
    }

    @Override
    public boolean tryLock(long waitTime, long leaseTime, TimeUnit timeUnit) throws InterruptedException {
        return redissonLock.tryLock(waitTime, leaseTime, timeUnit);
    }

    @Override
    public void unlock() {
        // 最佳实践：确保当前线程持有锁才能解锁
        if (redissonLock.isHeldByCurrentThread()) {
            redissonLock.unlock();
        }
    }
}
